<?php
namespace app\admin\controller;

use Qiniu\Auth;
use Qiniu\Storage\UploadManager;
use think\Controller;

class Base extends Controller
{
    public function _initialize()
    {
        $this->assign("url", request()->url());
        if (session("cms") == null) {
            $this->redirect("member/login");
        }
        $this->cms = session("cms");
        $this->assign("cms", $this->cms);
        $this->assign("qiniuprefix",config("qiniu.prefix"));
    }
    protected function qiniuupload($filename="file"){
        $qiniuconfig=config("qiniu");
        if(!request()->isPost()){
            return null;
        }
        if(empty($_FILES[$filename])){
            return null;
        }
        $file=$_FILES[$filename];
        if($file["error"]>0){
            return null;
        }
        $filename=$file["name"];
        $path=$file["tmp_name"];
        $ex=substr($filename, strrpos($filename, '.')+1);
        $key=guid().".".$ex;
        $accessKey = $qiniuconfig['ak'];
        $secretKey = $qiniuconfig['sk'];
        $auth = new Auth($accessKey, $secretKey);
        $bucket = $qiniuconfig['bucket'];;
        $token = $auth->uploadToken($bucket);
        $uploadMgr = new UploadManager();
        $uploadMgr->putFile($token, $key,$path);
        return $key;

    }


    protected function _edit($modelname, $data = [], $_where = [])
    {
        $id = input("get.id");
        $model = model($modelname);
        if (request()->post()) {
            if ($id != null) {
                $model->allowField(true)->save(array_merge($_POST, $data), array_merge(['id' => $id], $_where));
            } else {
                $model->allowField(true)->save(array_merge($_POST, $data));
            }
            return true;
        }


        if ($id != null) {
            $info = $model->get($id);
            $this->assign("info", $info);
        }
        return false;
    }


    protected function _delete($modelname, $where, $url)
    {
        $model = model($modelname);
        $model = $model->get($where);
        if ($model != null) {
            $model->delete();
        }
        $this->redirect($url);
    }

    protected function _list($modelname, $where,$_order="id asc")
    {
        $cate = model($modelname);
        $list = $cate->where($where)->order($_order)->paginate(10);

        $group_id=input("post.group_id");
        $list=Db::table("groups_followed")->order("id desc")->where("is_check",1)->where("group_id",$group_id)->paginate(10);
        $this->assign('list', $list);
    }
}
